<script setup>
import MainContainer from "@/components/MainContainer.vue";
import { ref } from 'vue'
import { roleGetList, getMenuList, getRoleMenuID, setRoleMenuID, roleDel, roleAdd, userGetListBySearch } from '@/api/setting'

const roleList = ref([])
const roleRef = ref('')
const menuRef = ref('')
const thisrole = ref({
  roleName: '',
  roleCode: '',
  description: ''
})
const menuList = ref('')
// const isEditRole = ref(false)
const roleProps = {
  label: 'roleName',

}
const isPermissionEdit = ref(false)
const menuProps = {
  label: 'name',
  disabled: () => { return !isPermissionEdit.value }
}
let menuID = []
const page = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const userList = ref([]);
// 页面初始化刷新，获取角色列表
const getRoleList = async () => {
  await roleGetList().then(res => {
    roleList.value = res.data.data
  })
  console.log(roleList.value)
}
getRoleList();


// 获取角色对应的信息列表
const handleRoleNode = async () => {
  console.log(roleRef.value.currentNode.data.id)
  thisrole.value.roleName = roleRef.value.currentNode.data.roleName
  thisrole.value.description = roleRef.value.currentNode.data.description
  thisrole.value.roleCode = roleRef.value.currentNode.data.roleCode.slice(5)
  await getRoleMenuID(roleRef.value.currentNode.data.id).then(res => {
    // console.log(res.data.data)
    menuID = res.data.data
    console.log(menuID)
  })
  await getMenuList().then(res => {
    console.log(res.data)
    menuList.value = res.data.data
  })
  // 获取当前角色的用户列表
  await userGetListBySearch({ roleId: roleRef.value.currentNode.data.id, page: page.value, pageSize: pageSize.value })
    .then((res) => {
      console.log(res.data)
      userList.value = res.data.data.records
      pageTotal.value = res.data.data.total
    })
  isPermissionEdit.value = false
}
// 删除角色
const delDialogVisable = ref(false)
const delRoleId = ref('')
const remove = (data) => {
  delDialogVisable.value = true
  delRoleId.value = data.id
  console.log(delRoleId.value)
}
const delRole = async () => {
  await roleDel(delRoleId.value).then((res) => {
    ElMessage.success(res.data.data)
    delRoleId.value = ''
    delDialogVisable.value = false
    getRoleList();
  })
}
// 新增角色
const addDialogVisable = ref(false)
const roleData = ref({
  roleName: '',
  roleCode: '',
  description: ''
})
const addRole = async () => {
  console.log(roleData.value)
  await roleAdd(roleData.value).then((res) => {
    console.log(res.data)
    ElMessage.success(res.data.data)
    addDialogVisable.value = false
    getRoleList()
  })
}

// 修改权限 并刷新权限页面

const handleMenu = async () => {
  console.log('roleid:', roleRef.value.currentNode.data.id)
  // menuRef.getCheckedKey
  console.log('menuId:', menuRef.value.getCheckedKeys())
  await setRoleMenuID(roleRef.value.currentNode.data.id, menuRef.value.getCheckedKeys()).then((res) => {
    if (res.data.success) {
      ElMessage.success('权限调整完成')
      isPermissionEdit.value = false
    }
  })
  await getRoleMenuID(roleRef.value.currentNode.data.id).then(res => {
    menuID = res.data.data
    console.log(menuID)
  })
}

</script>

<template>
  <main-container title="权限管理">
    <el-row class="main">
      <el-col :span="4" class="left">
        <p>角色列表</p>
        <el-button v-auth="['admin:permission:addRole']" type="primary" style="width: 90%; margin: 1rem 0;"
          @click="addDialogVisable = true;">新增角色</el-button>
        <el-tree ref="roleRef" :data="roleList" :props="roleProps" @node-click="handleRoleNode()" style="width: 80%; "
          highlight-current="true">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <a @click="getCurrentNode(data)"> <el-icon>
                    <Edit />
                  </el-icon> </a>
                <a v-auth="['admin:permission:delrole']" style="margin-left: 8px" @click="remove(data)"> <el-icon>
                    <DeleteFilled />
                  </el-icon> </a>
              </span>
            </span>
          </template>
        </el-tree>
      </el-col>
      <el-col :span="12" class="middle">
        <el-row class="roleInfo">
          <h4>角色信息</h4>
          <el-text tag="b">角色名称：{{ thisrole.roleName }} </el-text>
          <el-text tag="b">角色编码：{{ thisrole.roleCode }} </el-text>
          <el-text>角色描述：{{ thisrole.description }}</el-text>
        </el-row>

        <el-row class="roleUserTable">
          <h4>角色用户</h4>
          <el-table class="userTable" :data="userList" style="width: 100%;">
            <el-table-column header-align="center" align="center" type="index" label="序号" width="55"></el-table-column>
            <el-table-column header-align="center" align="center" prop="username" label="用户名"></el-table-column>
            <el-table-column header-align="center" align="center" prop="name" label="姓名"></el-table-column>
            <el-table-column header-align="center" align="center" prop="status" label="启用状态">
              <template #default="scope">
                <div>{{ scope.row.status === '1' ? "启用" : "停用" }}</div>
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" prop="dept" label="部门"></el-table-column>
            <el-table-column header-align="center" align="center" prop="job" label="岗位"></el-table-column>
          </el-table>
          <el-pagination class="pagination" v-model:current-page="page" v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]" small background layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal" @change="userGetListBySearch" />
        </el-row>
      </el-col>
      <el-col :span="8" class="right">
        <el-row class="permissions">
          <div class="permTitle">
            <h4>权限管理 </h4>
          </div>
          <el-text type="warning">- 仅选择父选项代表页面可被当前角色查看。</el-text>
          <el-text type="warning">- 如果选择了子选项，必须同步选择复选项，否则操作权限无页面可操作。</el-text>
          <el-tree ref="menuRef" class="filter-tree" :data="menuList" style="max-width: 600px; margin-left: 5%;"
            :props="menuProps" default-expand-all show-checkbox node-key="id" check-strictly
            :default-checked-keys="menuID" />
          <div class="menuBtn" v-auth="['admin:permission:setroleMenu']">
            <el-button v-if="isPermissionEdit" size="small" type="primary" style="width: 100px; margin: 20px 0;"
              @click="handleMenu">确定</el-button>
            <el-button v-if="!isPermissionEdit" size="small" style="width: 100px; margin: 20px 0;"
              @click="isPermissionEdit = true">编辑</el-button>
          </div>
        </el-row>
      </el-col>
    </el-row>
    <!-- 删除确认对话框 -->
    <el-dialog v-model="delDialogVisable" title="删除确认" width="500">
      <el-text type="danger"> 删除角色会影响已分配该权限的所有用户！</el-text>
      <template #footer>
        <div>
          <el-button @click="delDialogVisable = false" type="primary">取消</el-button>
          <el-button @click="delRole" type="danger">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增角色对话框 -->
    <el-dialog v-model="addDialogVisable" title="新增角色" width="500">
      <el-form :model="roleData" label-width="auto">
        <el-form-item required label="角色名称">
          <el-input v-model="roleData.roleName"></el-input>
        </el-form-item>
        <el-form-item required label="角色编码">
          <el-input v-model="roleData.roleCode" type="text" placeholder="请使用英文字母"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleData.description" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="addDialogVisable = false" type="primary">取消</el-button>
          <el-button @click="addRole" type="primary">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改角色 TODO -->
  </main-container>

</template>

<style scoped lang="less">
.main {
  min-height: 80vh;

  .left,
  .middle,
  .right {
    padding-left: 20px;

    .el-tree {
      height: 80%; // 
      background-color: transparent;
      // border: solid 1px;
      border-color: #DCDFE6;
      border-radius: 10px;
      padding: 10px;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
  }

  .roleInfo {
    display: flex;
    flex-direction: column;

    .el-text {
      display: block;
      align-self: flex-start;
      padding: 5px 10px;
    }
  }

  .right,
  .middle {
    border-left: 1px solid #e0e0e0;
  }

  .permissions {
    display: flex;
    position: relative;
    flex-direction: column;
    align-content: start;

    .el-text {
      margin-left: 20px;
      align-self: start;
    }

    .el-tree {
      margin-top: 20px;
    }

    .menuBtn {
      position: absolute;
      right: 100px;

      .el-button {
        margin-left: 10px
      }
    }
  }

}

.roleUserTable {
  display: flex;
  margin-top: 50px;

  .pagination {
    width: 100%;
    display: flex;
    justify-content: end;
    margin-top: 20px;
    margin-right: 50px;
  }
}

.delConfirm {
  height: 2rem;
  vertical-align: middle;
}

.filter-tree {
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}
</style>
